/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myservlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import search.Product;

/**
 *
 * @author Yasmani
 */
public class Search extends HttpServlet {
    
    
    private static final String URL = "jdbc:mysql://localhost:3306/ismi";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "isaac16";
    private Connection connection = null;
    private PreparedStatement select = null;
    private ResultSet rst = null;
    private String[] fields = {"name", "description", "partNumber", "manufacturer"};
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String s = request.getParameter("query");
        System.out.println(s);
        String indexPath = "C:/Users/Yasmani/Documents/NetBeansProjects/sematech/resources/index";
        try {
            
            
            Class.forName("com.mysql.jdbc.Driver");
            
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            
            select = connection.prepareStatement("select * from product");
            
            rst = select.executeQuery();
            
            
            
            
            StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);

         // 1. create the index
            
            
         Directory index = new RAMDirectory();

         IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
         config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

         IndexWriter w = new IndexWriter(index, config);
         
         while(rst.next()){
                    addDoc(w, rst.getString("product_id"), rst.getString("product_name"), 
                            rst.getString("product_description"), rst.getString("user_name")
                            ,rst.getString("product_picture"),rst.getString("product_price"), rst.getString("product_amount"),
                            rst.getString("part_number"), rst.getString("manufacturer"));
                    
         }
         
         w.close();
         

         // 2. query
         

         // the "title" arg specifies the default field to use
         // when no field is explicitly specified in the query.
         Query q = new MultiFieldQueryParser(Version.LUCENE_35, fields, analyzer).parse(s);

         // 3. search
         int hitsPerPage = 10;
         IndexReader reader = IndexReader.open(index);
         IndexSearcher searcher = new IndexSearcher(reader);
         TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
         searcher.search(q, collector);
         ScoreDoc[] hits = collector.topDocs().scoreDocs;
         
         // 4. display results
         List searchResults = new ArrayList();
         System.out.println("Found " + hits.length + " hits.");
         for(int i=0;i<hits.length;++i) {
           int docId = hits[i].doc;
           Document d = searcher.doc(docId);
           
       Product products = new Product(d.get("id"), d.get("name"),d.get("description"),d.get("user"),d.get("pic"),d.get("price"),d.get("amount"),
               d.get("partNumber"), d.get("manufacturer"));
           
           searchResults.add(products);
           
          
         }
         request.setAttribute("products", searchResults);
         request.getRequestDispatcher("searchResults.jsp").forward(request, response);

         // searcher can only be closed when there
         // is no need to access the documents any more. 
         //w.close();
         searcher.close();
        } catch (CorruptIndexException ex) {
            out.println(ex.getMessage());
        } catch (LockObtainFailedException ex) {
            out.println(ex.getMessage());
        } catch (IOException ex) {
            out.println(ex.getMessage());
        } catch (ParseException ex) {
            out.println(ex.getMessage());
        } catch (SQLException ex) {
            out.println(ex.getMessage());
        } catch (ClassNotFoundException ex) {
            out.println(ex.getMessage());
        }
        finally {            
            try{
                if(connection != null)
                    connection.close();
                if(rst != null)
                    rst.close();
            }
            catch (SQLException ex) {
            out.println(ex.getMessage());
        }
        }
    }
    
    private static void addDoc(IndexWriter w, String id, String name,  String desc, String user, String pic, String price, String amount, String partNumber, String manufacturer) throws IOException, SQLException {
    Document doc = new Document();
    doc.add(new Field("id", id, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("user", user, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("name", name, Field.Store.YES, Field.Index.ANALYZED));
    doc.add(new Field("description", desc, Field.Store.YES, Field.Index.ANALYZED));
    doc.add(new Field("pic", pic, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("price", price, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("amount", amount, Field.Store.YES, Field.Index.NO));
    doc.add(new Field("partNumber", partNumber, Field.Store.YES, Field.Index.ANALYZED));
    doc.add(new Field("manufacturer", manufacturer, Field.Store.YES, Field.Index.ANALYZED));
    w.addDocument(doc);
    
  }  

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
